package com.zztl.infiniteBand.util


import android.content.Context
import com.zztl.infiniteBand.model.CountryCodeBean
import java.util.*

/**
 * Created by kezq on 2017/11/23.
 */

class AlphaComparator(context: Context) : Comparator<CountryCodeBean.DataBean> {
    private val mCompat: AlphabeticIndexCustomCompat

    init {
        mCompat = AlphabeticIndexCustomCompat(context)
    }

    override fun compare(data1: CountryCodeBean.DataBean?, data2: CountryCodeBean.DataBean?): Int {
        return if (data1 != null && data2 != null) {
            compareIndex(data1, data2)
        } else {
            0
        }
    }

    private fun compareIndex(data1: CountryCodeBean.DataBean, data2: CountryCodeBean.DataBean): Int {
        val index1: Int
        val index2: Int
        var str1 = data1.countryName
        var str2 = data2.countryName
        if (str1 == null && str2 != null) {
            return 1
        } else if (str1 != null && str2 == null) {
            return -1
        } else if (str1 == null && str2 == null) {
            return 0
        }
        str1 = str1!!.toLowerCase()
        str2 = str2!!.toLowerCase()
        val s1 = mCompat.computeSectionName(str1)//首字母
        val s2 = mCompat.computeSectionName(str2)
        data1.firstLetter = s1
        data2.firstLetter = s2

        index1 = mCompat.getBucketIndex(s1)//字母顺序
        index2 = mCompat.getBucketIndex(s2)

        return if (index1 == 0 && index2 > 0) {
            1
        } else if (index2 == 0 && index1 > 0) {
            -1
        } else if (index1 == 0 && index2 == 0) {
            str1.compareTo(str2)
        } else if (index1 > index2) {
            1
        } else if (index1 < index2) {
            -1
        } else {
            str1.compareTo(str2)
        }
    }
}
